const User = require('../models/User')
const Article = require('../models/Article')
const Follow = require('../models/Follow')
const Key = require('../models/Key')
const sendToken = require('../utils/sendToken')
const {getPublicKey} = require('../utils/rsaControl')
const {pagination} = require('../utils/utils')
const {uploadURL, serverURL} = require("../config");
const mongoose = require('mongoose')
// 公钥
exports.get_PublicKey = async function (req, res, next) {
  try {
    const {content} = await Key.findOne()
    console.log('content: ', content)
    res.success({
      publicKey: content,
    })
  } catch (err) {
    console.log('-> err123:', err)
    let pubKey = await getPublicKey()
    const model = await Key.create({content: pubKey})
    next(err)
  }
}

//注册
exports.register = async (req, res, next) => {
  try {
    let user = await User.create(req.body)
    //生成token
    let token = await sendToken({_id: user._id, username: user.username})
    res.success(
      {
        userId: user._id,
        token: token,
      },
      '注册成功'
    )
  } catch (err) {
    console.log(err)
    next(err)
  }
}

// 登录
exports.login = async (req, res, next) => {
  try {
    //生成token
    const user = req.user
    let token = await sendToken({_id: user._id, username: user.username})
    res.success(
      {
        userId: user._id,
        token: token,
      },
      '登录成功'
    )
  } catch (err) {
    console.log(err)
    next(err)
  }
}

//获取单个用户信息
async function fetchUserStats(userId) {
  const objectIdUserId = new mongoose.Types.ObjectId(userId)
  const [followCount, articleCount, totalLikeNum, totalCommentNum, totalHitNum] = await Promise.all([
    Follow.aggregate([{$match: {followeeId: objectIdUserId}}, {$count: 'followCount'}]),
    Article.aggregate([{$match: {author: objectIdUserId}}, {$count: 'articleCount'}]),
    Article.aggregate([
      {$match: {author: objectIdUserId}},
      {$group: {_id: null, totalLikes: {$sum: '$like_num'}}},
    ]),
    Article.aggregate([
      {$match: {author: objectIdUserId}},
      {$group: {_id: null, totalComments: {$sum: {$size: '$comments'}}}},
    ]),
    Article.aggregate([
      {$match: {author: objectIdUserId}},
      {$group: {_id: null, totalHits: {$sum: '$hit_num'}}},
    ]),
  ])

  return {
    followCount: followCount.length ? followCount[0].followCount : 0,
    articleCount: articleCount.length ? articleCount[0].articleCount : 0,
    totalLikeNum: totalLikeNum.length ? totalLikeNum[0].totalLikes : 0,
    totalCommentNum: totalCommentNum.length ? totalCommentNum[0].totalComments : 0,
    totalHitNum: totalHitNum.length ? totalHitNum[0].totalHits : 0,
  }
}

//登录用户信息
exports.userinfo = async (req, res, next) => {
  let _id = req._id
  try {
    let userResult = await User.findById(_id)
    let userStats = await fetchUserStats(_id);
    userResult = userResult.toObject()
    userResult.articleCount = userStats.articleCount;
    userResult.totalLikeNum = userStats.totalLikeNum;
    userResult.totalCommentNum = userStats.totalCommentNum;
    userResult.totalHitNum = userStats.totalHitNum;
    res.success(userResult, '查询成功')
  } catch (err) {
    console.log(err)
    next(err)
  }
}
//获取作者信息
exports.authorinfo = async (req, res, next) => {
  const userId = req.params.id
  console.log('userId-----: ', userId)
  let _id = req._id
  try {
    let userResult = await User.findById(userId)
    let userStats = await fetchUserStats(userId);
    //登陆用户是否关注作者标示
    let isfollow = 0;
    console.log('_id---:', _id)
    if (_id) {
      var followRes = await Follow.find({
        followerId: _id,
        followeeId: userId
      })
      console.log('followRes!!!:', followRes)
      if (followRes.length > 0) {
        isfollow = 1
      }
    }
    userResult = userResult.toObject()
    let imgUrl = "";
    if (userResult.avatar === "/img/avatar.png") {
      imgUrl = serverURL + userResult.avatar;
    } else {
      imgUrl = uploadURL + userResult.avatar;
    }
    userResult.avatar = imgUrl;
    userResult.articleCount = userStats.articleCount;
    userResult.totalLikeNum = userStats.totalLikeNum;
    userResult.totalCommentNum = userStats.totalCommentNum;
    userResult.totalHitNum = userStats.totalHitNum;
    userResult.isfollow = isfollow
    res.success(userResult, '查询成功')
  } catch (err) {
    console.log(err)
    next(err)
  }
}

//获取用户列表
exports.userList = async (req, res, next) => {
  const pageNumber = req.query.pageNumber ? parseInt(req.query.pageNumber) : 1
  const pageSize = req.query.pageSize ? parseInt(req.query.pageSize) : 10
  try {
    // 调用分页方法
    const paginateResult = await pagination({
      model: User,
      select: '-createdAt',
      pageNumber,
      pageSize,
    })
    res.success(paginateResult, '查询成功')
  } catch (err) {
    console.log(err)
    next(err)
  }
}

//改变角色
exports.changeRole = async (req, res, next) => {
  const _id = req.body.id
  const roles = [req.body.roles]
  var json = {roles: roles}
  try {
    let data = await User.findByIdAndUpdate(_id, json, {new: true})
    res.success(data, '更新状态成功')
  } catch (err) {
    next(err)
  }
}

//修改密码
exports.changePwd = async (req, res, next) => {
  const _id = req.body._id
  const newPassword = req.body.newPassword
  var json = {password: newPassword}
  console.log(json);
  try {
    await User.findByIdAndUpdate(_id, json)
    res.success({isEdit: true}, '更新状态成功')
  } catch (err) {
    next(err)
  }
}
//修改作者信息
exports.updateAuthorInfo = async (req, res, next) => {
  const {_id, ...json} = req.body
  let {avatar} = json
  if (avatar.includes("/img/avatar.png")) {
    avatar = avatar.replace(serverURL, '')
  } else {
    avatar = avatar.replace(uploadURL, '')
  }
  json.avatar = avatar
  try {
    let data = await User.findByIdAndUpdate(_id, json, {new: true})
    res.success(data, '更新状态成功')
  } catch (err) {
    next(err)
  }
}
